import { createStore } from "@/vuex"; // new Store

function statePersistence ( store ) {
  const localState = sessionStorage.getItem( 'VUEX_STATE' );
  if ( localState ) {
    store.replaceState( JSON.parse( localState ) );
  }
  store.subscribe( ( { type }, state ) => {
    sessionStorage.setItem( 'VUEX_STATE', JSON.stringify( state ) );
  } )
}

const store = createStore( {
  plugins: [ statePersistence ],
  strict: true,
  state: {
    count: 10,
  },
  getters: {
    double ( state ) {
      return state.count * 2;
    },
  },
  mutations: {
    add ( state, payload ) {
      state.count += payload;
    },
  },
  actions: {
    asyncAdd ( { commit }, payload ) {
      return new Promise( ( resolve, reject ) => {
        setTimeout( () => {
          commit( "add", payload );
          resolve();
        }, 1000 );
      } );
    },
  },
  modules: {
    aCount: {
      namespaced: true,
      state: { count: 20 },
      mutations: {
        add ( state, payload ) {
          state.count += payload;
        },
      },
      modules: {
        cCount: {
          namespaced: true,
          state: { count: 30 },
          mutations: {
            add ( state, payload ) {
              state.count += payload
            }
          },
        }
      }
    },
    bCount: {
      namespaced: true,
      state: { count: 40 },
      mutations: {
        add ( state, payload ) {
          state.count += payload;
        },
      },
    },
  },
} );

export default store;
